package com.earthea.chatbot.controller;

import com.earthea.chatbot.entity.domain.Message;
import com.earthea.chatbot.entity.request.PublishMessageReq;
import com.earthea.chatbot.entity.response.MessageRsp;
import com.earthea.chatbot.entity.response.PublishMessageRsp;
import com.earthea.chatbot.login.common.util.SecurityUtils;
import com.earthea.chatbot.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

@RestController
@RequestMapping("/api/message")
public class MessageController {

    @Autowired
    private MessageService messageService;

    @GetMapping("/{chatId}")
    public MessageRsp list(@PathVariable String chatId) {
        Message message = new Message();
        message.setChatId(chatId);
        message.setUserId(SecurityUtils.getLoginUserId());
        return messageService.selectByChat(message);
    }

    @PostMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> stream(@RequestBody PublishMessageReq publishMessageReq) {
        Message message = new Message();
        message.setUserId(SecurityUtils.getLoginUserId());
        message.setChatId(publishMessageReq.getChatId());
        message.setRole("user");
        message.setContent(publishMessageReq.getContent());
        return messageService.stream(message);
    }

    @PostMapping("/block")
    public PublishMessageRsp block(@RequestBody PublishMessageReq publishMessageReq) {
        Message message = new Message();
        message.setUserId(SecurityUtils.getLoginUserId());
        message.setChatId(publishMessageReq.getChatId());
        message.setRole("user");
        message.setContent(publishMessageReq.getContent());
        return messageService.insert(message);
    }
}
